<?php
namespace app\manage\controller;

use app\manage\model\UserRole;
use think\Controller;
use think\migration\command\migrate\Status;
use think\Request;
use think\Validate;
use think\Db;
use Config;
use app\common\model\TokenCheck;
use app\manage\model\OperationLog;
use app\manage\model\AdminUser;

class Staff extends Controller{
    public function __construct(Request $request = null)
    {
//        parent::__construct($request);
    }

    /**
     * 显示员工
     * @param   keyword         关键字
     * @param   p               页码
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function showStaff() {
        $input = input();
        $keyword = isset($input['keyword']) ? trim($input['keyword']) : "";
        $page = isset($input['p']) ? trim($input['p']) : "";
        $department_id = isset($input['department_id']) ? trim($input['department_id']) : "";
        $create_id = isset($input['admin_id']) ? trim($input['admin_id']) : "";

        /**
         * 获取一页数据和总数，尚未进行错误判断与处理
         */
        $model=new AdminUser();
        $create_id = $model->findPlatId($create_id);
        $onePage = $model->onePage($page, get_list_rows(), $keyword, 2,$create_id, $department_id);
        $total = $model->total($keyword, 2, $create_id,$department_id);

        $data['total'] = $total;
        $data['data'] = $onePage;
        returnJson(200,"成功", $data)->send();die;
    }

    /**
     * 增加员工
     * @param   name    员工名称
     * @param   admin_pwd    密码
     * @param   job_number  工号
     * @param   sex         性别
     * @param   admin_tel  手机号
     * @param   department_id  部门id
     * @param   department_name  部门名
     * @param   role_id  角色id
     * @param   role_name  角色名
     */
    public function createStaff() {
        $input = input();
        $validate = new Validate([
            ['name', 'require|max:50', '名称不能为空|不能超过20字'],
            ['admin_pwd', 'require|min:6|max:256', '密码不能为空|密码长度不能小于6位|密码长度不能大于12位'],
            ['job_number', 'require', '工号不能为空'],
            ['sex', 'require', '性别不能为空'],
            ['admin_tel', 'require|max:11|/^1[3-8]{1}[0-9]{9}$/', '手机号码不能为空|手机号码不能超过11个字符|手机号码格式不正确'],
            ['department_id', 'require', '部门id不能为空'],
            ['role_id', 'require', '角色id不能为空']
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        /**
         * 员工表插入账户
         */
        $data['key'] = rand(100000, 999999);// 密码加密码
        $data['name'] = isset($input['name']) ? trim($input['name']) : "";
        $data['admin_pwd'] = isset($input['admin_pwd']) ? md5(trim($input['admin_pwd']).$data['key']) : "";
        $data['job_number'] = isset($input['job_number']) ? trim($input['job_number']) : "";
        $data['sex'] = isset($input['sex']) ? trim($input['sex']) : "";
        $data['admin_tel'] = isset($input['admin_tel']) ? trim($input['admin_tel']) : "";
        $data['department_id'] = isset($input['department_id']) ? trim($input['department_id']) : "";
        $data['role_id'] = isset($input['role_id']) ? trim($input['role_id']) : "";
        $data['create_id'] = isset($input['admin_id']) ? trim($input['admin_id']) : "";
        $data['icon'] = isset($input['icon']) ? trim($input['icon']) : "";
        $data['admin_status'] = 1;
        $data['admin_sign'] = 2;
        $data['create_time'] = time();
        $data['update_time'] = time();

        $model=new AdminUser();
        $data['create_id'] = $model->findPlatId($data['create_id']);
        // 验证唯一性
        if (($model->uniqueness($data['admin_tel'], $data['create_id'])) !== 0) {
            returnJson(-2012,"账号已存在")->send();die;
        }
        if (($model->uniqueness($data['admin_tel'])) !== 0) {
            returnJson(-2012,"账号已在其他平台存在")->send();die;
        }

        $addtextRes=$model->m_insert($data);
        if (!$addtextRes) {
            returnJson(-2001,"服务器错误")->send();die;
        }

        $model_role = new \app\manage\model\Role();
        $model_department = new \app\manage\model\Department();
        $role_info = $model_role->detail($data['role_id']);
        $value['role_name'] = $role_info['name'];
        $department_info = $model_department->detail($data['department_id']);
        $value['department_name'] = $department_info['name'];
        $updatetextRes = $model->m_update($addtextRes, $value);
        if (!$updatetextRes) {
            returnJson(-2013,"数据无变化")->send();die;
        }

        /**
         * 更新部门人数数量
         */
        $model = new \app\manage\model\Department();
        $edittextRes = $model->add($data['department_id']);
        if (!$edittextRes) {
            returnJson(-2001,"服务器错误")->send();die;
        }

        /**
         * 更新角色人数数量
         */
        $model = new \app\manage\model\Role();
        $edittextRes = $model->add($data['role_id']);
        if (!$edittextRes) {
            returnJson(-2001,"服务器错误")->send();die;
        }

        /**
         * 插入用户角色表
         */
        $model = new UserRole();
        $addtextRes=$model->setRoleRelation($addtextRes, $data['role_id']);
        if ($addtextRes) {
            returnJson(200,"成功", $addtextRes)->send();die;
        } else {
            returnJson(-2001,"服务器错误")->send();die;
        }
    }

    /**
     * 更新员工账户
     * @param   admin_id
     * @param   name    员工名称
     * @param   job_number  工号
     * @param   sex         性别
     * @param   admin_tel  手机号
     * @param   department_id  部门id
     * @param   department_name  部门名
     * @param   role_id  角色id
     * @param   role_name  角色名
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editStaff() {
        $input = input();
        $validate = new Validate([
            ['admin_id', 'require', '员工id不能为空'],
            ['name', 'require|max:50', '名称不能为空|不能超过20字'],
            ['job_number', 'require', '工号不能为空'],
            ['sex', 'require', '性别不能为空'],
            ['admin_tel', 'require|max:11|/^1[3-8]{1}[0-9]{9}$/', '手机号码不能为空|手机号码不能超过11个字符|手机号码格式不正确'],
            ['department_id', 'require', '部门id不能为空'],
            ['role_id', 'require', '角色id不能为空']
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $admin_id = isset($input['admin_id']) ? trim($input['admin_id']) : "";
        $data['name'] = isset($input['name']) ? trim($input['name']) : "";
        $data['job_number'] = isset($input['job_number']) ? trim($input['job_number']) : "";
        $data['sex'] = isset($input['sex']) ? trim($input['sex']) : "";
        $data['admin_tel'] = isset($input['admin_tel']) ? trim($input['admin_tel']) : "";
        $data['department_id'] = isset($input['department_id']) ? trim($input['department_id']) : "";
        $data['role_id'] = isset($input['role_id']) ? trim($input['role_id']) : "";
        $data['icon'] = isset($input['icon']) ? trim($input['icon']) : "";
        $data['update_time'] = time();

        /**
         * 获取员工所属角色id和部门id，若有变动，对应角色或部门表的统计数量需发生变化
         */
        $model=new AdminUser();
        $detail = $model->detail($admin_id, 2);
        $role_id = $detail['role_id'];
        $department_id = $detail['department_id'];

        /**
         * 编辑员工表
         */

        $edittextRes=$model->m_update($admin_id, $data);
//        if (!$edittextRes) {
//            returnJson(-2001,"服务器错误")->send();die;
//        }

        $model_role = new \app\manage\model\Role();
        $model_department = new \app\manage\model\Department();
        $role_info = $model_role->detail($data['role_id']);
        $value['role_name'] = $role_info['name'];
        $department_info = $model_department->detail($data['department_id']);
        $value['department_name'] = $department_info['name'];
        $updatetextRes = $model->m_update($admin_id, $value);
//        var_dump($updatetextRes);
//        if (!$updatetextRes) {
//            returnJson(-2001,"服务器错误")->send();die;
//        }

        /**
         * 编辑用户角色关联表
         */
        $model = new UserRole();
        $dataRoleAction['role_id'] = $data['role_id'];
        $edittextRes=$model->updateActionRelation($admin_id, $dataRoleAction['role_id']);
//        if (!$edittextRes) {
//            returnJson(-2001,"服务器错误")->send();die;
//        }

        /**
         * 若用户更改了角色id，则更新角色表中的统计用户数量
         */
        if ($role_id !== $data['role_id']) {
            $model = new \app\manage\model\Role();
            $model->del($role_id);
            $model->add($data['role_id']);
        }

        /**
         * 若用户更改了部门id，则更新部门表中的统计用户数量
         */
        if ($department_id !== $data['department_id']) {
            $model = new \app\manage\model\Department();
            $model->del($department_id);
            $model->add($data['department_id']);
        }
        returnJson(200,"成功")->send();die;
    }

    /**
     * @param   admin_id
     * @param   admin_pwd
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function updatePassword() {
        $input = input();
        $validate = new Validate([
            ['admin_id', 'require', '员工id不能为空'],
            ['admin_pwd', 'require|min:6|max:256', '密码不能为空|密码长度不能小于6位|密码长度不能大于12位'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $admin_id = isset($input['admin_id']) ? trim($input['admin_id']) : "";
        $data['admin_pwd'] = isset($input['admin_pwd']) ? trim($input['admin_pwd']) : "";

        // 获取密码加密时的key
        $model=new AdminUser();
        $key_info = $model->getKey($admin_id);
        $key = $key_info['key'];

        $data['admin_pwd'] = md5($data['admin_pwd'] . $key);
        $edittextRes = $model->m_update($admin_id, $data);
        if ($edittextRes) {
            returnJson(200,"成功")->send();die;
        } else {
            returnJson(-2013,"数据无变化")->send();die;
        }
    }

    /**
     * @param   admin_id
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function deleteStaff() {
        $input = input();
        $validate = new Validate([
            ['admin_id', 'require', '平台id不能为空']
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $admin_id = isset($input['admin_id']) ? trim($input['admin_id']) : "";

        /**
         * 找到对应的部门id与角色id，均减少一人
         */
        $model=new AdminUser();
        $detail = $model->detail($admin_id, 2);
        $role_id = $detail['role_id'];
        $department_id = $detail['department_id'];

        $data['admin_status'] = 3;
        $deletetextRes=$model->m_update($admin_id, $data);
        if (!$deletetextRes) {
            returnJson(-2013,"数据无变化")->send();die;
        }

        $model = new \app\manage\model\Role();
        $model->del($role_id);
        $model = new \app\manage\model\Department();
        $model->del($department_id);
        returnJson(200,"成功")->send();die;
    }

    /**
     * @param   admin_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detailStaff() {
        $input = input();
        $validate = new Validate([
            ['admin_id', 'require', '平台id不能为空']
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $admin_id = isset($input['admin_id']) ? trim($input['admin_id']) : "";

        $model=new AdminUser();
        $detailtextRes=$model->detail($admin_id, 2);
        if (!$detailtextRes) {
            returnJson(-2001,"服务器错误")->send();die;
        }

        returnJson(200,"成功", $detailtextRes)->send();die;
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDepartment() {
        $model=new \app\manage\model\Department();
        $admin_id = get_user_id(input()['token']);
        $admin_id = $model->findPlatId($admin_id);
        $detailtextRes=$model->getAll($admin_id);
        returnJson(200,"成功", $detailtextRes)->send();die;

    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRole() {
        $model=new \app\manage\model\Role();
        $admin_id = get_user_id(input()['token']);
        $admin_id = $model->findPlatId($admin_id);
        $detailtextRes=$model->getAll($admin_id);
        returnJson(200,"成功", $detailtextRes)->send();die;
    }

}